<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getClazzListApi,
  addClazzApi,
  updateClazzApi,
  deleteClazzApi,
  getClazzByIdApi,
} from '@/api/clazz'
import type { ClazzModel } from '@/api/model/model'

const tableData = ref<ClazzModel[]>([])
const total = ref(0)
const loading = ref(false)
const query = ref({
  name: '',
  begin: '',
  end: '',
  page: 1,
  pageSize: 10,
})

const dialogVisible = ref(false)
const dialogTitle = ref('添加班级')
const form = ref<Partial<ClazzModel>>({})

const fetchData = async () => {
  loading.value = true
  const res = await getClazzListApi(query.value)
  // 防御性处理，防止res.data为undefined时报错
  tableData.value = res && res.data && res.data.rows ? res.data.rows : []
  total.value = res && res.data && res.data.total ? res.data.total : 0
  loading.value = false
}

onMounted(() => {
  fetchData()
})

const handleSearch = () => {
  query.value.page = 1
  fetchData()
}

const handleReset = () => {
  query.value.name = ''
  query.value.begin = ''
  query.value.end = ''
  query.value.page = 1
  fetchData()
}

const handleAdd = () => {
  dialogTitle.value = '添加班级'
  form.value = {}
  dialogVisible.value = true
}

const handleEdit = async (row: ClazzModel) => {
  const res = await getClazzByIdApi(Number(row.id))
  dialogTitle.value = '编辑班级'
  form.value = { ...res.data }
  dialogVisible.value = true
}

const handleDelete = (row: ClazzModel) => {
  ElMessageBox.confirm('确定要删除该班级吗？', '提示', { type: 'warning' }).then(async () => {
    await deleteClazzApi(Number(row.id))
    ElMessage.success('删除成功')
    fetchData()
  })
}

const handleSubmit = async () => {
  // 类型转换，防止字符串传给后端
  if (form.value.masterId) form.value.masterId = Number(form.value.masterId)
  if (form.value.subject) form.value.subject = Number(form.value.subject)
  if (form.value.id) {
    await updateClazzApi(form.value as ClazzModel)
    ElMessage.success('修改成功')
  } else {
    await addClazzApi(form.value as ClazzModel)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  fetchData()
}
</script>

<template>
  <div class="ai-bg">
    <div class="emp-container ai-glass">
      <div class="emp-header">
        <h1>班级管理</h1>
        <el-button class="ai-btn" @click="handleAdd">新增班级</el-button>
      </div>
      <el-form :inline="true" class="emp-search" @submit.prevent="handleSearch">
        <el-form-item label="班级名称">
          <el-input v-model="query.name" placeholder="班级名称" clearable />
        </el-form-item>
        <el-form-item label="开课时间">
          <el-date-picker
            v-model="query.begin"
            type="date"
            placeholder="开始日期"
            style="width: 140px"
          />
        </el-form-item>
        <el-form-item label="结课时间">
          <el-date-picker
            v-model="query.end"
            type="date"
            placeholder="结束日期"
            style="width: 140px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSearch" class="ai-btn">查询</el-button>
          <el-button @click="handleReset" class="ai-btn" style="margin-left: 8px">重置</el-button>
        </el-form-item>
      </el-form>
      <el-card class="table-card ai-glass">
        <el-table :data="tableData" border style="width: 100%" :loading="loading" class="emp-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="name" label="班级名称" align="center" />
          <el-table-column prop="room" label="教室" align="center" />
          <el-table-column prop="beginDate" label="开课时间" align="center" />
          <el-table-column prop="endDate" label="结课时间" align="center" />
          <el-table-column prop="masterName" label="班主任" align="center" />
          <el-table-column prop="subject" label="学科" align="center" />
          <el-table-column prop="status" label="状态" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="action-group">
                <el-button class="action-btn ai-btn" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button class="action-btn ai-btn ai-btn-danger" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="query.page"
          :page-size="query.pageSize"
          :total="total"
          layout="prev, pager, next, jumper"
          @current-change="fetchData"
          class="emp-pagination"
        />
      </el-card>
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500"
        class="emp-dialog ai-glass"
      >
        <el-form :model="form" label-width="90px">
          <el-form-item label="班级名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="教室">
            <el-input v-model="form.room" />
          </el-form-item>
          <el-form-item label="开课时间">
            <el-date-picker v-model="form.beginDate" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="结课时间">
            <el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="班主任ID">
            <el-input v-model="form.masterId" />
          </el-form-item>
          <el-form-item label="学科">
            <el-input v-model="form.subject" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" class="ai-btn" @click="handleSubmit">提交</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped></style>
